import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import Tagger.AutoTagAlgorithm;

public class FileContentAutoTagAlgorithm implements AutoTagAlgorithm {
	private HashMap<String,HashSet<String>> fromKeyWordsToTagsTable;
	private HashSet<String> keyWords;
	public FileContentAutoTagAlgorithm(){
		
		fromKeyWordsToTagsTable=new HashMap<String,HashSet<String>>();
		keyWords=new HashSet<String>();
		
		//search for "PathAuotTagAlgorithm.txt" file ,to get users definitions for mapping keywords to tags.		
		Path file = Paths.get("FileContentAutoTagAlgorithm.txt"); //here the text file should be.
		
	
		if(file.exists())//case the file "FileContentAutoTagAlgorithm.txt" exists, build attributes from it.
		{
			buildFromFile(file);
		}
		else //case the file not exist. create it with default values, and build attributes from it.
		{
			//create it with default values
			
			BufferedWriter out=null;
			try {
				out = new BufferedWriter(new FileWriter(file.toString())); 
				
				//default values.
				String[] data={"operation systems:windows,linux,solaris",
							   "studies:grade,lecture,exercise",
							   "family:dad,mom,brother,sister",
							   "cars:Jaguar,Aston Martin,Honda,Fiat,Rover,BMW",
							   "body:heart,liver,brain,kidneys,lungs",
							   "flowers:tulip,orchid,rose,daisy,daffodil,lily",
							   "valueable stones:diamond,opal,ruby,emerald,jade,sapphire",
							   "weather:rainy,sunny,foggy,cloudy,snowy",
							   "dogs:rottweiller,dalmatian,husky,labrador,boxer,poodle,pit bull,collie",
							   "fashion:Dolce and Gabbana,Versace,Chanel,Gucci,Dior,Armani",
							   "jobs:nurse,laboratory technician,cashier,doctor,dentist,teacher,actor",
							   "cosmetics:lipstick,mascara,foundation,eye shadow",
							   "money:euro,dollar,pound,yen",
							   "cartoon:Scooby Doo,The Simpsons,Mickey Mouse,Tom and Jerry,Bugs Bunny,Beavis and Butthead",
							   "england:Birmingham,Bristol,Liverpool,Leeds,Oxford,Cambridge",
							   "icecraem:strawberry,chocolate,vanilla,coffee,rum and raisin",
							   
					 		  };
				int size=data.length;
				for(int i=0 ; i<size ; i++){
					out.write(data[i]);
					out.newLine();
				}
			} 
			catch (IOException x) {
			}
			 //close the file
			finally {
			    if (out != null)
					try {
						out.flush();
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
			
			//build attributes from it.
			buildFromFile(file);
		}
	}
	
	//This method build ,keyWords and fromKeyWordsToTagsTable attributes, from a file.  
	public void buildFromFile(Path file ){
		InputStream in = null;
		try {
		    in = file.newInputStream();
		    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		    String line = null;int size;
		    //get a line, break it into peaces, and case syntax is good put it in 'fromKeyWordsToTagsTable' table.
		    while( (line = reader.readLine()) != null) {
		    	line.toLowerCase();
		    	String[] sepetare=line.split(":");
		    	if(sepetare.length!=2){//case wrong syntax - continue to next row.
		    		System.out.println("worng syntax on FileContentAutoTagAlgorithm.txt file !");
		    		continue;
		    	}
		    	String[] data=sepetare[1].split(",");
		    	
		    	size=data.length;
		    	// for every key word at that row. notice that data[0] contains a tag, and data[2]...data[n] contains keywords. 
		    	for(int i=0;i<size;i++){ 
		    		if(keyWords.contains(data[i])){//case the keyword already exist add the tag (data[0]) to its HashSet.
		    			fromKeyWordsToTagsTable.get(data[i]).add(sepetare[0]);
		    		}
		    		else{//put the keyword in keyWords table and in fromKeyWordsToTagsTable with it's tag.(data[0])
		    			keyWords.add(data[i]);
		    			HashSet<String> x= new HashSet<String>();
		    			x.add(sepetare[0]);
		    			fromKeyWordsToTagsTable.put(data[i],x);
		    		}
		    	}
		    	
		    }
		    
		} 
		catch (IOException x) {
		}
		 //close the file
		finally {
		    if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	public String getInfo() {
			return "This Algorithm returns tags \naccordimg to key words in \nfile content and only if \nit is a text file\n.  you can set the mapping \nfrom key words to tags your \nself, by changing the \n'FileContentAutoTagAlgorithm.txt' file. \nenjoy.";
	}

	public String[] getTagsForFile(File file) {
		//turn the file to path.
		Path p = file.toPath();
		String fileType=null;
		try {
			fileType=Files.probeContentType(p);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(fileType!=null&&fileType.startsWith("text")){//case it is a text file, get its tags.
			
			HashSet<String> result=new HashSet<String>();//will get all the tags.
			HashMap<String,Integer> tempmap=new HashMap<String,Integer>();
			InputStream in = null;
			try {
			    in = p.newInputStream();
			    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			    String line = null;int size;
			    //get a line, break it into peaces, and case syntax is good put it in 'fromKeyWordsToTagsTable' table.
			    while( (line = reader.readLine()) != null) {	
			    	line.toLowerCase();
			    	String[] data=line.split("\\W");
			    	size=data.length;
			    	// for every key word at that row. notice that data[0] contains a tag, and data[1]...data[n] contains keywords. 
			    	for(int i=0;i<size;i++){ 
			    		if(keyWords.contains(data[i])){//case the keyword already exist add the tag (data[0]) to its HashSet.
			    			result.addAll(fromKeyWordsToTagsTable.get(data[i]));
			    		}
			    	}		    	
			    }			    
			} 
			catch (IOException x) {
			}
			 //close the file
			finally {
			    if (in != null)
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
			/*
			if(tempmap.size()<=5){
				
				String[] a=new String[tempmap.size()];
				return tempmap.keySet().toArray(a);
			}
			else{
				HashMap<String,Integer> res=new HashMap<String,Integer>();
				Set<String> tempset=tempmap.keySet();
				Iterator<String> it=tempset.iterator();
				for(int i=0;i<5;i++){
					String str=it.next();
					res.put(str,tempmap.get(str));
				}
				while(it.hasNext()){
					Set<String> d=res.keySet();
					String toComp=it.next();
					boolean replaced=false;
					Iterator<String> itt=d.iterator();
					while(itt.hasNext()&&!replaced){
						String str1=itt.next();
						if(res.get(str1).intValue()<tempmap.get(toComp).intValue()){
							res.remove(str1);
							res.put(toComp, tempmap.get(toComp));
							replaced=true;
						}
					}
				}
				String[] a=new String[res.size()];
				return res.keySet().toArray(a);
			}*/
			result.remove(null);
			String[] a=new String[result.size()];
			return  result.toArray(a);
		
		}
		else{
			return null;	
		}
	}

}
